<template>
	<view class="container">
		<view class="weight-card">
			<view class="weight-info">
				<view class="initial-weight">
					<text class="label">初始体重</text>
					<text class="value">{{initialWeight}}kg</text>
				</view>
				<view class="current-weight">
					<text class="label" style="color: red;">当前体重</text>
					<text class="value" style="color: red;">{{currentWeight}}kg</text>
				</view>
				<view class="weight-target">
					<text class="label">目标体重</text>
					<text class="value">{{targetWeight}}kg</text>
				</view>
			</view>
			<view class="weight-progress">
				<u-line-progress :percentage="weightProgress" :show-text="false" activeColor="#018d71"
					inactiveColor="#f0f0f0" height="10"></u-line-progress>
				<text class="progress-text">已减重 {{weightLoss.toFixed(2)}}kg</text>
			</view>
		</view>

		<view class="bmi-card">
			<view class="bmi-header">
				<text class="title">BMI 指数</text>
				<view class="height-edit" @tap="showHeightEdit">
					<text>身高: {{height}}cm</text>
					<u-icon name="edit-pen" size="16" color="#666"></u-icon>
				</view>
			</view>
			<view class="bmi-content">
				<text class="bmi-value" :class="bmiStatus.class">{{bmi}}</text>
				<text class="bmi-status" :class="bmiStatus.class">{{bmiStatus.text}}</text>
			</view>
		</view>

		<view class="weight-history">
			<view class="u-flex u-flex-y-center u-flex-between" style="margin-bottom: 20rpx;">
				<view class="section-title">体重记录</view>
				<view class="section-title" style="font-size: 24rpx;" @click="more">查看更多</view>
			</view>
			<view class="history-list">
				<view class="history-item" v-for="(item, index) in weightHistory" :key="index" v-if="index<=4">
					<view class="date">{{$u.timeFormat((new Date(item.date).getTime()), 'yyyy年mm月dd日 hh:MM:ss')}}</view>
					<view class="weight">{{item.weight}}kg</view>
					<view class="change" :class="item.change >= 0 ? 'up' : 'down'">
						{{item.change >= 0 ? '+' : ''}}{{item.change}}kg
					</view>
				</view>
			</view>
		</view>

		<view class="action-buttons">
			<u-button type="primary" @tap="showWeightEdit">更新体重</u-button>
			<u-button type="info" @tap="showTargetEdit">设置目标</u-button>
			<u-button type="warning" @tap="showInitialEdit">设置初始</u-button>
		</view>

		<!-- 身高编辑弹窗 -->
		<u-popup :show="showHeightPopup" mode="center" width="80%" :round="10">
			<view class="popup-content">
				<view class="popup-title">编辑身高</view>
				<u-number-box v-model="tempHeight" inputWidth='200rpx' :max="250"></u-number-box>
				<view class="popup-buttons">
					<u-button @tap="showHeightPopup = false">取消</u-button>
					<u-button type="primary" @tap="confirmHeight" :loading="btnloading"  text="确定"></u-button>
				</view>
			</view>
		</u-popup>

		<!-- 体重编辑弹窗 -->
		<u-popup :show="showWeightPopup" mode="center" width="80%" :round="10">
			<view class="popup-content">
				<view class="popup-title">更新体重</view>
				<u-number-box v-model="tempWeight" inputWidth='200rpx' :max="200" :step="0.1"></u-number-box>
				<view class="upload-section">
					<text class="upload-title">上传体重图片</text>
					<u-upload :file-list="fileList" @afterRead="afterRead" @delete="deletePic" :max-count="1"
						accept="image" :width="100" :height="100"></u-upload>
				</view>
				<view class="popup-buttons">
					<u-button @tap="showWeightPopup = false">取消</u-button>
					<u-button type="primary" @tap="confirmWeight" :loading="btnloading" text="确定"></u-button>
				</view>
			</view>
		</u-popup>

		<!-- 目标体重编辑弹窗 -->
		<u-popup :show="showTargetPopup" mode="center" width="80%" :round="10">
			<view class="popup-content">
				<view class="popup-title">设置目标体重</view>
				<u-number-box v-model="tempTargetWeight" inputWidth='200rpx' :max="200" :step="0.1"></u-number-box>
				<view class="popup-buttons">
					<u-button @tap="showTargetPopup = false">取消</u-button>
					<u-button type="primary" @tap="confirmTarget" :loading="btnloading" text="确定"></u-button>
				</view>
			</view>
		</u-popup>

		<!-- 初始体重编辑弹窗 -->
		<u-popup :show="showInitialPopup" mode="center" width="80%" :round="10">
			<view class="popup-content">
				<view class="popup-title">设置初始体重</view>
				<u-number-box v-model="tempInitialWeight" inputWidth='200rpx' :max="200" :step="0.1"></u-number-box>
				<view class="popup-buttons">
					<u-button @tap="showInitialPopup = false">取消</u-button>
					<u-button type="primary" @tap="confirmInitial" :loading="btnloading" text="确定"></u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				initialWeight: 0,
				currentWeight: 0,
				targetWeight: 0,
				weightLoss: 0,
				weightProgress: 0,
				height: 0,
				bmi: 0,
				btnloading:false,
				bmiStatus: {
					text: '',
					class: ''
				},
				weightHistory: [],
				showHeightPopup: false,
				showWeightPopup: false,
				showTargetPopup: false,
				showInitialPopup: false,
				tempHeight: 0,
				tempWeight: 0,
				tempTargetWeight: 0,
				tempInitialWeight: 0,
				fileList: []
			}
		},
		computed: {
			// 计算BMI
			computedBmi() {
				if (!this.currentWeight || !this.height) return 0
				return (this.currentWeight / (this.height / 100) ** 2).toFixed(1)
			},
			
			// BMI状态
			computedBmiStatus() {
				const bmi = this.computedBmi
				if (bmi < 18.5) {
					return {
						text: '偏瘦',
						class: 'thin'
					}
				} else if (bmi < 24) {
					return {
						text: '正常',
						class: 'normal'
					}
				} else if (bmi < 28) {
					return {
						text: '偏胖',
						class: 'overweight'
					}
				} else {
					return {
						text: '肥胖',
						class: 'obese'
					}
				}
			}
		},
		onShow() {
			this.loadData()
		},
		methods: {
			// 加载数据
			more(){
				uni.navigateTo({
					url:'/pages/index/more'
				})
			},
			async loadData() {
				try {
					const {
						result: userinfo
					} = await uniCloud.callFunction({
						name: 'user',
						data: {
							action: 'getuser',
							token: uni.getStorageSync('jfToken')
						}
					})
					if (userinfo.code == 0) {
						uni.setStorageSync('jfuserinfo', userinfo.data)
						this.initialWeight = userinfo.data.cs.csweight
						this.targetWeight = userinfo.data.mb.mbweight
						this.height = userinfo.data.height
					}else{
						uni.reLaunch({
							url:'/pages/login/login'
						})
					}
					if(!this.initialWeight&&!this.targetWeight){
						uni.$u.toast('请先设置初始体重和目标体重')
						return
					}
					// 获取体重历史记录
					const {
						result: historyResult
					} = await uniCloud.callFunction({
						name: 'weight',
						data: {
							action: 'getList',
							token: uni.getStorageSync('jfToken')
						}
					})

					if (historyResult.code === 0) {
						this.weightHistory = historyResult.data.map((item, index) => {
							const prevWeight = index < historyResult.data.length - 1 ? historyResult.data[
								index + 1].weight : item.weight
							return {
								...item,
								change: (item.weight - prevWeight).toFixed(1)
							}
						})
						if (this.weightHistory.length > 0) {
							this.currentWeight = this.weightHistory[0].weight
							this.weightLoss = this.initialWeight - this.currentWeight
							this.weightProgress = (this.weightLoss / (this.initialWeight - this.targetWeight)) * 100
						}
					}
					if(historyResult.code==-1){
						uni.reLaunch({
							url:'/pages/login/login'
						})
					}
					// 更新BMI
					this.updateBmi()
				} catch (e) {
					uni.showToast({
						title: '加载数据失败',
						icon: 'none'
					})
				}
			},

			// 更新BMI
			updateBmi() {
				this.bmi = this.computedBmi
				this.bmiStatus = this.computedBmiStatus
			},

			// 显示修改身高弹窗
			showHeightEdit() {
				this.tempHeight = this.height
				this.showHeightPopup = true
			},

			// 确认身高修改
			async confirmHeight() {
				if(this.btnloading){
					return
				}
				this.btnloading=true
				try {
					const {
						result
					} = await uniCloud.callFunction({
						name: 'user',
						data: {
							action: 'updateHeight',
							token: uni.getStorageSync('jfToken'),
							data: {
								height: this.tempHeight
							}
						}
					})
					if (result.code === 0) {
						this.height = this.tempHeight
						this.showHeightPopup = false
						uni.showToast({
							title: '设置成功',
							icon: 'success'
						})
						this.btnloading=false
						this.updateBmi()
					} else {
						uni.showToast({
							title: result.msg,
							icon: 'none'
						})
						this.btnloading=false
					}
				} catch (e) {
					this.btnloading=false
					uni.showToast({
						title: '设置失败',
						icon: 'none'
					})
				}
				
			},

			// 显示初始体重编辑弹窗
			showInitialEdit() {
				this.tempInitialWeight = this.initialWeight
				this.showInitialPopup = true
			},

			// 确认初始体重修改
			async confirmInitial() {
				if(this.btnloading){
					return
				}
				this.btnloading=true
				try {
					const {
						result
					} = await uniCloud.callFunction({
						name: 'user',
						data: {
							action: 'updatecsweight',
							token: uni.getStorageSync('jfToken'),
							data: {
								csweight: this.tempInitialWeight
							}
						}
					})

					if (result.code === 0) {
						this.initialWeight = this.tempInitialWeight
						this.showInitialPopup = false
						uni.showToast({
							title: '设置成功',
							icon: 'success'
						})
						this.loadData()
					} else {
						uni.showToast({
							title: result.msg,
							icon: 'none'
						})
					}
					this.btnloading=false
				} catch (e) {
					this.btnloading=false
					uni.showToast({
						title: '设置失败',
						icon: 'none'
					})
				}
			},

			// 显示体重编辑弹窗
			showWeightEdit() {
				this.tempWeight = this.currentWeight
				this.fileList = []
				this.showWeightPopup = true
			},

			// 确认体重修改
			async confirmWeight() {
				if(this.btnloading){
					return
				}
				this.btnloading=true
				try {
					if (!this.tempWeight) {
						uni.showToast({
							title: '请输入体重',
							icon: 'none'
						})
						return
					}

					// 上传图片
					let image = ''
					if (this.fileList.length > 0) {
						const uploadRes = await uniCloud.uploadFile({
							filePath: this.fileList[0].thumb,
							cloudPath: `weight/${Date.now()}-${Math.random().toString(36).slice(-6)}.jpg`
						})
						image = uploadRes.fileID
					}

					// 添加体重记录
					const {
						result
					} = await uniCloud.callFunction({
						name: 'weight',
						data: {
							action: 'add',
							token: uni.getStorageSync('jfToken'),
							data: {
								weight: this.tempWeight,
								image
							}
						}
					})

					if (result.code === 0) {
						uni.showToast({
							title: '记录成功',
							icon: 'success'
						})
						this.showWeightPopup = false
					} else {
						uni.showToast({
							title: result.msg,
							icon: 'none'
						})
					}
					let _this=this
					setTimeout(()=>{
						_this.loadData()
					},100)
					this.btnloading=false
				} catch (e) {
					uni.showToast({
						title: '记录失败',
						icon: 'none'
					})
					this.btnloading=false
				}
			},

			// 显示目标体重编辑弹窗
			showTargetEdit() {
				this.tempTargetWeight = this.targetWeight
				this.showTargetPopup = true
			},

			// 确认目标体重修改
			async confirmTarget() {
				if(this.btnloading){
					return
				}
				this.btnloading=true
				try {
					const {
						result
					} = await uniCloud.callFunction({
						name: 'user',
						data: {
							action: 'updatembweight',
							token: uni.getStorageSync('jfToken'),
							data: {
								mbweight: this.tempTargetWeight
							}
						}
					})

					if (result.code === 0) {
						this.targetWeight = this.tempTargetWeight
						this.showTargetPopup = false
						uni.showToast({
							title: '设置成功',
							icon: 'success'
						})
					} else {
						uni.showToast({
							title: result.msg,
							icon: 'none'
						})
					}
					this.btnloading=false
				} catch (e) {
					console.error('设置目标体重失败：', e)
					uni.showToast({
						title: '设置失败',
						icon: 'none'
					})
					this.btnloading=false
				}
				
			},

			// 格式化日期
			formatDate(date) {
				const d = new Date(date)
				return `${d.getMonth() + 1}月${d.getDate()}日`
			},

			// 上传图片后
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: result,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				console.log(this.fileList)
				
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx;

		.weight-card {
			background-color: #ffffff;
			border-radius: 20rpx;
			padding: 30rpx;
			margin-bottom: 30rpx;

			.weight-info {
				display: flex;
				justify-content: space-between;
				margin-bottom: 20rpx;

				.current-weight,
				.weight-target,
				.initial-weight {
					text-align: center;
					flex: 1;

					.label {
						font-size: 24rpx;
						color: #666;
						display: block;
						margin-bottom: 10rpx;
					}

					.value {
						font-size: 48rpx;
						font-weight: bold;
						color: #018d71;
					}
				}
			}

			.weight-progress {
				.progress-text {
					font-size: 24rpx;
					color: #666;
					text-align: right;
					display: block;
					margin-top: 10rpx;
				}
			}
		}

		.bmi-card {
			background-color: #ffffff;
			border-radius: 20rpx;
			padding: 30rpx;
			margin-bottom: 30rpx;

			.bmi-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;

				.title {
					font-size: 32rpx;
					font-weight: bold;
				}

				.height-edit {
					display: flex;
					align-items: center;
					color: #666;
					font-size: 24rpx;

					.u-icon {
						margin-left: 10rpx;
					}
				}
			}

			.bmi-content {
				text-align: center;

				.bmi-value {
					font-size: 72rpx;
					font-weight: bold;
					color: #018d71;
					display: block;
					margin-bottom: 10rpx;

					&.thin {
						color: #ffa940;
					}

					&.normal {
						color: #018d71;
					}

					&.overweight {
						color: #ff7a45;
					}

					&.obese {
						color: #ff4d4f;
					}
				}

				.bmi-status {
					font-size: 28rpx;

					&.thin {
						color: #ffa940;
					}

					&.normal {
						color: #018d71;
					}

					&.overweight {
						color: #ff7a45;
					}

					&.obese {
						color: #ff4d4f;
					}
				}
			}
		}

		.weight-history {
			background-color: #ffffff;
			border-radius: 20rpx;
			padding: 30rpx;
			margin-bottom: 30rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				
			}

			.history-list {
				.history-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx 0;
					border-bottom: 1rpx solid #f0f0f0;

					&:last-child {
						border-bottom: none;
					}

					.date {
						font-size: 24rpx;
						color: #666;
					}

					.weight {
						font-size: 28rpx;
						font-weight: bold;
					}

					.change {
						font-size: 24rpx;

						&.up {
							color: #ff4d4f;
						}

						&.down {
							color: #018d71;
						}
					}
				}
			}
		}

		.action-buttons {
			display: flex;
			justify-content: space-between;
			gap: 20rpx;

			.u-button {
				flex: 1;
			}
		}

		.popup-content {
			padding: 30rpx;
			width: 600rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.popup-title {
				font-size: 32rpx;
				font-weight: bold;
				text-align: center;
				margin-bottom: 30rpx;
			}

			.upload-section {
				width: 100%;
				margin: 30rpx 0;

				.upload-title {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 20rpx;
					display: block;
				}

				::v-deep .u-upload {
					width: 100%;
				}
			}

			.popup-buttons {
				display: flex;
				justify-content: space-between;
				gap: 20rpx;
				margin-top: 30rpx;
				width: 600rpx;

				.u-button {
					flex: 1;
				}
			}
		}
	}
</style>